import globalDefine from "@/config/globalDefine"
import dayjs from "dayjs"
import CryptoJS from 'crypto-js'

const SECRET_KEY = 'weixiangshipu_2025_key'

export const handleImgSrc = (avatar: string | null | undefined): string => {
  if (!avatar || typeof avatar !== 'string') return ''
  const isHttps = avatar.trim().toLowerCase().startsWith('https')

  return isHttps ? avatar : globalDefine.staticUrl + avatar
}

export const changeTime = (time: number, format = 'YYYY-MM-DD') => {
  if (!time) return ''
  const tempTime = (time + '').length > 10 ? time : time * 1000
  return dayjs(tempTime).format(format)
}

export const isMobile = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

// 是否是微信浏览器
export const isWechat = (): boolean => {
  if (typeof navigator === 'undefined') return false
  const userAgent = navigator.userAgent.toLowerCase()
  return /micromessenger/.test(userAgent)
}

export const debounce = <T extends (...args: any[]) => void>(
  func: T,
  delay = 1000,
  immediate = false
) => {
  let timer: NodeJS.Timeout | null = null

  return function (this: any, ...args: Parameters<T>) {
    if (timer) clearTimeout(timer)

    // 立即执行，且当前没有定时器，就立即执行
    if (immediate && !timer) func.apply(this, args)

    timer = setTimeout(() => {
      // 非立即执行，就在延迟后执行
      if (!immediate) {
        func.apply(this, args)
      }
      timer = null
    }, delay)
  }
}

// 数据加密
export const encryptData = (data: string): string => {
  return CryptoJS.AES.encrypt(data, SECRET_KEY).toString()
}
// 数据解密
export const decryptData = (encryptedData: string): string => {
  const bytes = CryptoJS.AES.decrypt(encryptedData, SECRET_KEY)
  return bytes.toString(CryptoJS.enc.Utf8)
}

/**
 * 关键词高亮
 * @param text 原文本
 * @param keyword 关键词
 * @param className 高亮样式类名
 * @returns 高亮后的HTML字符串
 */
export const highlightKeyword = (text: string, keyword: string, className = 'highlight'): string => {
  if (!text || !keyword) return text
  const regex = new RegExp(`(${keyword})`, 'gi')
  return text.replace(regex, `<span class="${className}">$1</span>`)
}
